package com.example.mediaplayer.service;

import java.util.List;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.example.mediaplayer.base.BaseApp;
import com.example.mediaplayer.domain.FileInfo;
import com.example.mediaplayer.utils.ViewUtil;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;

/**
 * @author 作者ylh E-mail:504367857@qq.com
 * @version 创建时间：2015-1-18 下午4:33:14 类说明
 */
public class MyService extends Service implements
		MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
		MediaPlayer.OnCompletionListener {
	private static final String ACTION_PLAY = "com.share.ylh.mediaplayer.topreview";
	private int STATE = 0;// 1:play,2:psuse,3:stop;4:顺序播放;5：单曲循环播放；6：随机；7：上一首
							// 8：下一首

	private boolean ispause = false;
	// 文件id
	private static int id;
	private DbUtils db;
	List<FileInfo> list;
	MediaPlayer mp = null;
	private int barProgress;
	private Handler mHandler;
	private IntentFilter intentFilter = null;

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		initDatas();// 实例化数据库
		if (mp == null) {
			mp = new MediaPlayer();
		}

		registerReceiver(receiver, init());
		Log.e("service BroadcastReceiver ", "注册广播");

		startService();
		return super.onStartCommand(intent, flags, startId);
	}

	private void startService() {

		mHandler = new Handler();
		try {
			if (mp != null && STATE == 2 && !ispause) {
				Log.e("startService pause", "" + STATE);
				mp.pause();
				ispause = true;
			}
		} catch (Exception e) {
			Log.e("Service pause Exception", "Service pause Exception");
			ispause = true;
		}

		try {
			if (STATE == 1) {
				if (ispause) {
					mp.start();
					ispause = false;

				} else {
					initMediaPlayer(id);
				}
			}
		} catch (Exception e) {
			Log.e("Service start Exception", "Service start Exception");
			ispause = false;
		}
	}
	
	 //更新ui进度条
    private Runnable mRunnable = new Runnable() {

        @Override
        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                Intent intent = new Intent("com.share.ylh.mediaplayer.broatcast");

                try {
                    //暂停后切换 异常 进行捕获
                    intent.putExtra("Current", mp.getCurrentPosition());

                } catch (Exception e) {
                    intent.putExtra("Current", 0);
                }

                try {
                    //重新选歌 异常 进行捕获
                    intent.putExtra("Duration", mp.getDuration());

                } catch (Exception e) {
                    intent.putExtra("Duration", 0);
                }

                //发送广播，更新进度条
                BaseApp.AppContext.sendBroadcast(intent);


                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };

	private void initDatas() {
		try {
			db = DbUtils.create(this);
			list = db.findAll(FileInfo.class);// 通过类型查找
		} catch (DbException e) {
			e.printStackTrace();
		}
	}

	private void initMediaPlayer(int id) {

		synchronized (this) {
			ViewUtil.setShardPString("id", id + "");

			try {
				mp.reset();
				// mp=MediaPlayer.create(MyActivity.this,Uri.parse(list.get(id).getFilePath()));
				// 设置指定的流媒体地址
				mp.setDataSource(list.get(id).getFilePath());

				// 设置音频流的类型
				mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
				mp.setOnPreparedListener(this);
				mp.setOnErrorListener(this);
				mp.setOnCompletionListener(this);

				// 通过异步的方式装载媒体资源
				mp.prepareAsync();

			} catch (Exception e) {

				mp = null;
				initMediaPlayer(id);
			}
		}
	}

	@Override
	public boolean onError(MediaPlayer mp, int what, int extra) {
		try {
			/* 发生错误时也解除资源与MediaPlayer的赋值 */
			mp.release();
		} catch (Exception e) {

			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void onCompletion(MediaPlayer mediaPlayer) {
		// 一首歌播放完后执行
		try {
			/* 解除资源与MediaPlayer的赋值关系让资源可以为其它程序利用 */
			String ps = ViewUtil.getShardPStringByKey("playstate");
			if ("4".equals(ps)) {
				// 顺序播放
				repeatPlayer();

			} else if ("5".equals(ps)) {
				// 重复
				mediaPlayer.start();

			} else if ("6".equals(ps)) {
				int ramdom = ViewUtil.getRandam(0, list.size());
				 //随机
				initMediaPlayer(ramdom);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onPrepared(MediaPlayer mediaPlayer) {

		mediaPlayer.start();
		new Thread(mRunnable).start();

	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	/**
	 * 顺序播放
	 */
	private void repeatPlayer() {
		id = id + 1;
		if (id <= list.size()) {
			initMediaPlayer(id);
		} else {
			initMediaPlayer(0);
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		// 解除注册
		Toast.makeText(BaseApp.AppContext, "解除注册", Toast.LENGTH_SHORT).show();
		unregisterReceiver(receiver);
	}

	private IntentFilter init() {
		if (intentFilter == null) {
			intentFilter = new IntentFilter();
			intentFilter.addAction(ACTION_PLAY);

		}
		return intentFilter;
	}

	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {

			id = Integer.parseInt(ViewUtil.getShardPStringByKey("id"));
			STATE = Integer.parseInt(ViewUtil.getShardPStringByKey("STATE"));
			Log.e("startService", id + "&&" + STATE);

			if (intent.getAction()
					.equals(ACTION_PLAY)) {
				Log.e("service BroadcastReceiver ", "接收广播");

				if ("9".equals(ViewUtil.getShardPStringByKey("STATE"))) {
					initMediaPlayer(id);
				} else {
					startService();
				}
			}
		}
	};
}
